package cn.com.shadowless.xinning.view.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mengpeng.mphelper.ToastUtils;

import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.TrainOrderInfo;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;

/**
 * The type Train fragment.
 *
 * @author sHadowLess
 */
public class TrainFragment extends BaseFragment {

    /**
     * The Train receipt info receipt num.
     */
    @BindView(R.id.train_receiptInfo_ReceiptNum)
    TextView trainReceiptInfoReceiptNum;
    /**
     * The Train receipt info make time.
     */
    @BindView(R.id.train_receiptInfo_MakeTime)
    TextView trainReceiptInfoMakeTime;
    /**
     * The Train receipt info maker.
     */
    @BindView(R.id.train_receiptInfo_Maker)
    TextView trainReceiptInfoMaker;
    /**
     * The Train receipt info making depart.
     */
    @BindView(R.id.train_receiptInfo_MakingDepart)
    TextView trainReceiptInfoMakingDepart;
    /**
     * The Train receipt info position job.
     */
    @BindView(R.id.train_receiptInfo_PositionJob)
    TextView trainReceiptInfoPositionJob;
    /**
     * The Train personal details proposer.
     */
    @BindView(R.id.train_personalDetails_Proposer)
    TextView trainPersonalDetailsProposer;
    /**
     * The Train personal details proposer depart.
     */
    @BindView(R.id.train_personalDetails_ProposerDepart)
    TextView trainPersonalDetailsProposerDepart;
    /**
     * The Train personal details position.
     */
    @BindView(R.id.train_personalDetails_Position)
    TextView trainPersonalDetailsPosition;
    /**
     * The Train personal details work number.
     */
    @BindView(R.id.train_personalDetails_WorkNumber)
    TextView trainPersonalDetailsWorkNumber;
    /**
     * The Train personal details sex.
     */
    @BindView(R.id.train_personalDetails_Sex)
    TextView trainPersonalDetailsSex;
    /**
     * The Train personal details birth day.
     */
    @BindView(R.id.train_personalDetails_BirthDay)
    TextView trainPersonalDetailsBirthDay;
    /**
     * The Train personal details education.
     */
    @BindView(R.id.train_personalDetails_Education)
    TextView trainPersonalDetailsEducation;
    /**
     * The Train personal details date of entry.
     */
    @BindView(R.id.train_personalDetails_DateOfEntry)
    TextView trainPersonalDetailsDateOfEntry;
    /**
     * The Train train info train date.
     */
    @BindView(R.id.train_trainInfo_TrainDate)
    TextView trainTrainInfoTrainDate;
    /**
     * The Train train info train local.
     */
    @BindView(R.id.train_trainInfo_TrainLocal)
    TextView trainTrainInfoTrainLocal;
    /**
     * The Train train info content.
     */
    @BindView(R.id.train_trainInfo_Content)
    TextView trainTrainInfoContent;
    /**
     * The Train together.
     */
    @BindView(R.id.train_Together)
    LinearLayout trainTogether;
    /**
     * The Train training cost training course cost.
     */
    @BindView(R.id.train_trainingCost_TrainingCourseCost)
    TextView trainTrainingCostTrainingCourseCost;
    /**
     * The Train training cost people num.
     */
    @BindView(R.id.train_trainingCost_PeopleNum)
    TextView trainTrainingCostPeopleNum;
    /**
     * The Train training cost all money.
     */
    @BindView(R.id.train_trainingCost_AllMoney)
    TextView trainTrainingCostAllMoney;
    /**
     * The Train other other info.
     */
    @BindView(R.id.train_other_OtherInfo)
    TextView trainOtherOtherInfo;
    /**
     * The Train other groom cost total.
     */
    @BindView(R.id.train_other_GroomCostTotal)
    TextView trainOtherGroomCostTotal;
    /**
     * The Train other is suspend.
     */
    @BindView(R.id.train_other_IsSuspend)
    TextView trainOtherIsSuspend;
    /**
     * The Train other remark.
     */
    @BindView(R.id.train_other_Remark)
    TextView trainOtherRemark;
    /**
     * The Train depart training all info.
     */
    @BindView(R.id.train_departTraining_AllInfo)
    TextView trainDepartTrainingAllInfo;
    /**
     * The Train check process.
     */
    @BindView(R.id.train_check_Process)
    LinearLayout trainCheckProcess;

    private final String url = "api/EducationAppForm/LoadCheckHistory?%s=";
    private final String forMat = "%s\n公司预算金额：%s\n已报销：%s\n已申请未报销：%s\n报销中：%s\n在申请未报销：%s\n剩余可报销：%s\n剩余可申请：%s";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_train_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            initTrainOrderInfo(orderId, userName);
            initCheckHistoryList(String.format(url, "id") + orderId, mActivity, trainCheckProcess);
        }
    }

    @Override
    protected void initView() {

    }

    private void initTrainOrderInfo(String orderId, String userName) {
        OrderPresenter
                .getSingleton()
                .getTrainOrderInfo(orderId, userName, new RequestCallBack<TrainOrderInfo>() {
                    @Override
                    public void success(RequestResult<TrainOrderInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                TrainOrderInfo.DataBean dataBean = result.getResult().getData();
                                TrainOrderInfo.DataBean.CreateUserObjectBean createUserObjectBean = dataBean.getCreateUserObject();
                                TrainOrderInfo.DataBean.ApplicantObjectBean applicantObjectBean = dataBean.getApplicantObject();
                                TrainOrderInfo.DataBean.BudgetItemObjectBean budgetItemObjectBean = dataBean.getBudgetItemObject();
                                List<TrainOrderInfo.DataBean.ItemListBean> itemListBeans = dataBean.getItemList();

                                String id = dataBean.getId();
                                String createTimeStr = dataBean.getCreateTimeStr();
                                String createUserName = dataBean.getCreateUserName();
                                String departmentName = dataBean.getDepartmentName();
                                String positionName = createUserObjectBean.getPositionName();
                                trainReceiptInfoReceiptNum.setText(id);
                                trainReceiptInfoMakeTime.setText(createTimeStr);
                                trainReceiptInfoMaker.setText(createUserName);
                                trainReceiptInfoMakingDepart.setText(departmentName);
                                trainReceiptInfoPositionJob.setText(positionName);

                                String userName = applicantObjectBean.getUserName();
                                String account = applicantObjectBean.getAccount();
                                String genderStr = applicantObjectBean.getGenderStr();
                                String birthdayStr = applicantObjectBean.getBirthdayStr();
                                String education = applicantObjectBean.getEducationStr();
                                String workTimeStr = applicantObjectBean.getWorkTimeStr();
                                trainPersonalDetailsProposer.setText(userName);
                                trainPersonalDetailsProposerDepart.setText(departmentName);
                                trainPersonalDetailsPosition.setText(positionName);
                                trainPersonalDetailsWorkNumber.setText(account);
                                trainPersonalDetailsSex.setText(genderStr);
                                trainPersonalDetailsBirthDay.setText(birthdayStr);
                                trainPersonalDetailsEducation.setText(education);
                                trainPersonalDetailsDateOfEntry.setText(workTimeStr);

                                String cultivateAddress = dataBean.getCultivateAddress();
                                String cultivateStartTimeStr = dataBean.getCultivateStartTimeStr();
                                String cultivateEndTimeStr = dataBean.getCultivateEndTimeStr();
                                String cultivateDay = dataBean.getCultivateDay() + "";
                                String cultivateContent = dataBean.getCultivateContent();
                                trainTrainInfoTrainDate.setText(cultivateStartTimeStr + "至" + cultivateEndTimeStr + "\n" + "共" + cultivateDay + "天");
                                trainTrainInfoTrainLocal.setText(cultivateAddress);
                                trainTrainInfoContent.setText(cultivateContent);

                                for (TrainOrderInfo.DataBean.ItemListBean itemListBean : itemListBeans) {
                                    View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_train_tab_item, null);
                                    LinearLayout tab = view.findViewById(R.id.train_tab_Item);
                                    TextView people = view.findViewById(R.id.train_tab_People);
                                    TextView department = view.findViewById(R.id.train_tab_DepartName);
                                    TextView positon1 = view.findViewById(R.id.train_tab_Position);
                                    TextView phone = view.findViewById(R.id.train_tab_Phone);
                                    TrainOrderInfo.DataBean.ItemListBean.EducationUserObjectBean educationUserObjectBean = itemListBean.getEducationUserObject();
                                    String name = educationUserObjectBean.getUserName();
                                    String depart = educationUserObjectBean.getDepartmentName();
                                    String position = educationUserObjectBean.getPositionName();
                                    String telephone = educationUserObjectBean.getTelephone();
                                    people.setText(name);
                                    department.setText(depart);
                                    positon1.setText(position);
                                    phone.setText(telephone);
                                    trainTogether.addView(tab);
                                }

                                String cultivateCost = getDecimal(dataBean.getCultivateCost().doubleValue());
                                String cultivatePeopleCount = getDecimal(dataBean.getCultivatePeopleCount().doubleValue());
                                String cultivateTotalCost = getDecimal(dataBean.getCultivateTotalCost().doubleValue());
                                trainTrainingCostAllMoney.setText(cultivateCost);
                                trainTrainingCostPeopleNum.setText(cultivatePeopleCount);
                                trainTrainingCostTrainingCourseCost.setText(cultivateTotalCost);

                                String otherCost = dataBean.getOtherCost() + "";
                                String totalCostStr = dataBean.getTotalCostStr();
                                boolean isTemp = dataBean.isTemp();
                                String remark = dataBean.getRemark();
                                trainOtherOtherInfo.setText(otherCost);
                                trainOtherGroomCostTotal.setText(totalCostStr);
                                if (isTemp) {
                                    trainOtherIsSuspend.setText("√ 暂支");
                                } else {
                                    trainOtherIsSuspend.setText("X 不暂支");
                                }
                                trainOtherRemark.setText(remark);

                                String budgetInfo = budgetItemObjectBean.getBudgetInfo();
                                String allMoney = getDecimal(budgetItemObjectBean.getAllMoney().doubleValue());
                                String reimbursedMoney = getDecimal(budgetItemObjectBean.getReimbursedMoney().doubleValue());
                                String reimbursingMoney = getDecimal(budgetItemObjectBean.getReimbursingMoney().doubleValue());
                                String remainReimburseMoney = getDecimal(budgetItemObjectBean.getRemainReimburseMoney().doubleValue());
                                String applyedMoney = getDecimal(budgetItemObjectBean.getApplyedMoney().doubleValue());
                                String applyingMoney = getDecimal(budgetItemObjectBean.getApplyingMoney().doubleValue());
                                String remainApplyMoney = getDecimal(budgetItemObjectBean.getRemainApplyMoney().doubleValue());
                                String costInfo = String.format(
                                        forMat,
                                        budgetInfo,
                                        allMoney,
                                        reimbursedMoney,
                                        reimbursingMoney,
                                        remainReimburseMoney,
                                        applyedMoney,
                                        applyingMoney,
                                        remainApplyMoney
                                );
                                trainDepartTrainingAllInfo.setText(costInfo);
                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("该订单暂无详细信息");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }
}
